package com.smart.wap.service;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import com.smart.manager.finance.entities.enums.AppType;
import com.smart.manager.finance.entities.enums.PayPlatform;
import com.smart.manager.finance.entities.enums.PayState;
import com.smart.manager.finance.entities.models.FinanceCurrencyTariff;
import com.smart.manager.finance.entities.models.FinanceOrderCoin;
import com.smart.manager.finance.repository.CurrencyTariffRepository;
import com.smart.manager.member.entities.views.MemberView;
import com.smart.manager.finance.entities.models.FinanceOrderPop;
import com.smart.manager.pop.entities.models.PopDisInviter;
import com.smart.manager.pop.entities.models.PopDisLevel;
import com.smart.manager.pop.entities.models.query.QPopDisInviter;
import com.smart.manager.pop.entities.views.InviterView;
import com.smart.manager.pop.repository.DisLevelRepository;
import com.smart.wap.bodys.OpenIdKind;
import com.smart.wap.bodys.PaymentBody;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author Administrator
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class PaymentService {

    private final CurrencyTariffRepository tariffRepository;


    public FinanceOrderCoin createCoinOrder(Long memberId, PaymentBody.CreateOrderBody body) {
        FinanceCurrencyTariff currencyTariff = tariffRepository.getOne(body.getTariffId());
        BigDecimal payAmount = currencyTariff.getPayAmount();
        //玩家实际得到的金币
        int coinTotal = currencyTariff.getBestowCoin() + currencyTariff.getBaseCoin();
        Assert.isTrue(payAmount.compareTo(BigDecimal.ZERO) > 0, "充值失败:系统配置错误：订单应付配置小于等于0");
        Assert.isTrue(coinTotal > 0, "订单创建失败:用户实的金币不能小于1");
        String tradeNo = generateTradeNo();
        MemberView member = new MemberView().setId(memberId);

        FinanceOrderCoin orderCoin = new FinanceOrderCoin();

        orderCoin.setOrderId(tradeNo).setTariff(currencyTariff.getId())
                .setMember(member).setActionTime(LocalDateTime.now())
                .setPayState(PayState.NOT_PAID).setAppType(AppType.APP)
                .setAppId(body.getAppId())
                .setPayPlatform(body.getPayPlatform())
                .setAttached("会员账户充值")
                .setCoinTotal(coinTotal)
                .setFee(payAmount);
        orderCoin.save();
        return orderCoin;

    }




    /**
     * 生成订单id 长度为25个随机字符串
     *
     * @return {@code String}
     */
    private String generateTradeNo() {
        String x = DateUtil.format(new Date(), "yyyyMMddHHmmss").concat(RandomUtil.randomNumbers(5));
        return "CZ".concat(x);
    }



}
